<template>
  <div>
    <!-- 新增款式弹窗 -->
    <el-dialog
      v-model="editReasonDialogShow"
      width="80%"
      title="款式资讯"
      @close="closeDialog"
    >
      <div class="gva-table-box">
        <div class="role">
          <LTable
            :columns="columns"
            :tableData="tableData"
            :pages="pages"
            :maxHeight="'500px'"
            :searchArr="searchArr"
            :isSearch="true"
            @onSubmit="onSubmit"
            @updateMultipleSelection="handleSelectionChange"
            @changePages="changePages"
          >
          </LTable>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            :disabled="multipleSelection.length != 1"
            @click="save"
            >确定</el-button
          >
          <el-button @click="closeDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createProductStyles,
  deleteProductStyles,
  deleteProductStylesByIds,
  updateProductStyles,
  findProductStyles,
  getProductStylesList,
} from "@/api/plmProductStyles";
import { findSbuProjects } from "@/api/plmSbuProjects";
import { getSysDictionaryDetailList } from "@/api/sysDictionaryDetail"; // 获取字典
import { getSbuDataList } from "@/api/confSbuData";
import { getSbuProjectsList } from "@/api/plmSbuProjects";
// 全量引入格式化工具 请按需保留
import {
  getDictFunc,
  formatDate,
  formatBoolean,
  filterDict,
  ReturnArrImg,
  onDownloadFile,
} from "@/utils/format";
import { useDict } from "@/utils/dictionary.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
// 引入组件
import LTable from "@/components/LTable/LTable.vue";
import { useI18n } from "vue-i18n";
const { t: il8n } = useI18n();
const emit = defineEmits(["closeDialog", "selectStyleNum"]);
const props = defineProps({
  // elementui table props
  searchType: {
    type: Array,
    default: "",
  },
});
defineOptions({
  name: "ProductStyles",
});
// 路由操作
const router = useRouter();

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  styleNum: "",
  projectNum: "",
  cumstomerNum: "",
  customerStyleNum: "",
  updateUser: "",
  UpdatedAt: new Date(),
  status: "",
});

// 验证规则
const rule = reactive({});

// =========== 表格控制部分 ===========
const tableData = ref([]);
const pages = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});
const searchInfo = ref({});

const CreatedAtFilters = computed(() => {
  return tableData.value.map((item) => {
    return { text: formatDate(item.CreatedAt), value: item.CreatedAt };
  });
});
const UpdatedAtFilters = computed(() => {
  return tableData.value.map((item) => {
    return { text: formatDate(item.UpdatedAt), value: item.UpdatedAt };
  });
});

// ======表格头部数据======
const columns = ref([
  {
    prop: "styleNum",
    label: "款式编号",
    width: 130,
    show: true,
    filter: true,
    isSearch: true,
    // slot: "styleNum",
    tableColumnProps: {
      fixed: "left",
    },
  },
  {
    prop: "customerStyleNum",
    width: 130,
    label: "客户款号",
    show: true,
    filter: true,
    isSearch: true,
  },
  {
    prop: "cumstomerNum",
    label: "客户编号",
    width: 120,
    show: true,
    filter: true,
    isSearch: true,
  },
  {
    prop: "customerBrand",
    label: "品牌",
    width: 130,
    show: true,
    filter: true,
    isSearch: true,
  },
  {
    prop: "localStyleNum",
    label: "本厂款号",
    width: 160,
    show: true,
    filter: true,
    isSearch: true,
  },
]);
// ======查询数据======
const searchArr = ref([
  {
    prop: "styleNum",
    label: "款式编号",
    show: true, // 通过 show 来控制列的展示或隐藏
    value: "",
    type: "input",
  },
  {
    prop: "customerStyleNum",
    width: 200,
    label: "客户款号",
    show: true,
    type: "input",
    value: "",
  },
  {
    prop: "cumstomerNum",
    label: "客户编号",
    show: true,
    value: "",
    type: "input",
  },
  {
    prop: "customerBrand",
    label: "品牌",
    show: true,
    value: "",
    type: "input",
  },

  {
    prop: "localStyleNum",
    label: "本厂款号",
    show: true,
    value: "",
    type: "input",
  },
]);

// 重置
const onReset = () => {
  searchInfo.value = {};
  getTableData();
};

// 搜索
const onSubmit = (val) => {
  searchInfo.value = {
    ...val,
  };
  // if (searchInfo.value.CreatedAt) {
  //     searchInfo.value["startCreatedAt"] =
  //         searchInfo.value.CreatedAt[0] || "";
  //     searchInfo.value["endCreatedAt"] = searchInfo.value.CreatedAt[1] || "";
  // }
  // if (searchInfo.value.UpdatedAt) {
  //     searchInfo.value["startUpdatedAt"] =
  //         searchInfo.value.UpdatedAt[0] || "";
  //     searchInfo.value["endUpdatedAt"] = searchInfo.value.UpdatedAt[1] || "";
  // }
  pages.value.page = 1;
  pages.value.pageSize = 10;
  getTableData();
};

// 改变页码
const changePages = (currentPages) => {
  pages.value = {
    ...pages.value,
    ...currentPages,
  };
  getTableData();
};

// 查询
const getTableData = async () => {
  let datas =  {
      page: pages.value.page,
      pageSize: pages.value.pageSize,
      ...searchInfo.value,
      status: 1,
      searchType: props.searchType,
    }
    if(props.searchType) {
      datas.productSpecStatus = 1
    }
  const table = await getProductStylesList(datas);
  if (table.code === 0) {
    tableData.value = table.data.list.map((item) => {
      item["updateUser"] = item.updatedBySysUser?.userName;
      item.status = item.status == 1 ? "已确认" : "草稿";
      return item;
    });
    pages.value.total = table.data.total;
    pages.value.page = table.data.page;
    pages.value.pageSize = table.data.pageSize;
  }
};

getTableData();

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {};

// 获取需要的字典 可能为空 按需保留
setOptions();

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteProductStylesFunc(row);
  });
};

// 多选删除
const onDelete = async () => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const IDs = [];
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: "warning",
        message: "请选择要删除的数据",
      });
      return;
    }
    multipleSelection.value &&
      multipleSelection.value.map((item) => {
        IDs.push(item.ID);
      });
    const res = await deleteProductStylesByIds({ IDs });
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      if (tableData.value.length === IDs.length && pages.value.page > 1) {
        pages.value.page--;
      }
      getTableData();
    }
  });
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 更新行
const updateProductStylesFunc = async (row) => {
  // const res = await findProductStyles({ ID: row.ID });
  type.value = "update";
  router.push({
    path: "/layout/productStylesAdd",
    query: { id: row.ID },
  });
};

// 删除行
const deleteProductStylesFunc = async (row) => {
  const res = await deleteProductStyles({ ID: row.ID });
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    if (tableData.value.length === 1 && pages.value.page > 1) {
      pages.value.page--;
    }
    getTableData();
  }
};

// 打开详情
const getDetails = async (row, action) => {
  router.push({
    path: "/layout/ProductStylesView",
    query: {
      id: row.ID,
      action,
      subTitle: "款" + row.styleNum,
    },
  });
};

// 相关
const currentRow = ref({});
const dialogVisible = ref(false);
const relatedFun = (row) => {
  dialogVisible.value = true;
  currentRow.value = row;
};

// sub列表
const sbuOptions = ref([]);
// 获取sbu列表
const getSbuData = async (keyword) => {
  await getSbuDataList({ page: 1, pageSize: 100, sbuName: keyword }).then(
    (res) => {
      if (res.code === 0) {
        sbuOptions.value = res.data.list;
      }
    }
  );
};

// 新增款式改版---------------------------------------------------------------
const editReasonDialogShow = ref(true);
const projectListOptions = ref([]); // 项目编号列表
const addForm = ref({
  projectNum: "",
  num: 1,
});

// 查询项目编号列表
const remoteMethodProject = async (keyword) => {
  const table = await getSbuProjectsList({
    page: 1,
    pageSize: 30,
    projectNum: keyword ? keyword : undefined,
  });
  if (table.code === 0) {
    projectListOptions.value = table.data.list;
  }
};

// 关弹窗
const closeDialog = () => {
  emit("closeDialog");
};

// 新增提交
const save = async () => {
  emit("selectStyleNum", multipleSelection.value[0]);
};

onMounted(async () => {
  useDict(
    "frameMaterials",
    "glassFrameCate",
    "frameCate",
    "productGender"
  ).then((d) => {
    // 字典列表
    let list = searchArr.value.map((item) => {
      if (item.prop == "frameMaterial") {
        item["selectList"] = [...d.frameMaterials];
      }
      if (item.prop == "glassFrameCate") {
        item["selectList"] = [...d.glassFrameCate];
      }
      if (item.prop == "frameCate") {
        item["selectList"] = [...d.frameCate];
      }
      if (item.prop == "gender") {
        item["selectList"] = [...d.productGender];
      }
      return item;
    });
    searchArr.value = [];
    searchArr.value = [...list];
  });
});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");

:deep(.el-input-number .el-input__inner) {
  text-align: left;
  padding: 0 11px;
}
</style>
